<template>
  <div class="pollution-tracing" :key="$route.fullPath">
    <!-- 顶部标题 -->
    <header class="page-header">
      <h1>灵璧县人工智能产业园污染融合溯源分析</h1>
      <div class="current-time">{{ currentTime }}</div>
    </header>

    <div class="page-content">
      <!-- 左侧面板 -->
      <section class="left-panel">
        <div class="panel-item tracing-type">
          <h3>溯源类型</h3>
          <div class="type-selector">
            <div 
              v-for="(type, index) in tracingTypes" 
              :key="index"
              :class="['type-item', { active: currentType === type.id }]"
              @click="currentType = type.id"
            >
              <div class="type-icon" :class="type.icon"></div>
              <div class="type-name">{{ type.name }}</div>
            </div>
          </div>
        </div>
        
        <div class="panel-item source-list">
          <h3>可能污染源</h3>
          <div class="source-table-container">
            <table class="source-table">
              <thead>
                <tr>
                  <th>企业名称</th>
                  <th>污染类型</th>
                  <th>匹配度</th>
                  <th>距离</th>
                </tr>
              </thead>
              <tbody>
                <tr 
                  v-for="(source, index) in filteredSources" 
                  :key="index"
                  :class="{ selected: selectedSource === source.id }"
                  @click="selectSource(source.id)"
                >
                  <td>{{ source.name }}</td>
                  <td>{{ source.pollutionType }}</td>
                  <td>
                    <div class="match-bar-container">
                      <div class="match-bar" :style="{ width: source.matchRate + '%', backgroundColor: getMatchColor(source.matchRate) }"></div>
                      <span>{{ source.matchRate }}%</span>
                    </div>
                  </td>
                  <td>{{ source.distance }}km</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <div class="panel-item tracing-analysis">
          <h3>溯源分析</h3>
          <div ref="tracingChartRef" class="chart-container"></div>
        </div>
      </section>

      <!-- 右侧面板 -->
      <section class="right-panel">
        <div class="panel-item tracing-map">
          <h3>溯源地图</h3>
          <div ref="mapContainer" class="map-container"></div>
        </div>
        
        <div class="panel-item source-detail" v-if="selectedSourceDetail">
          <h3>污染源详情</h3>
          <div class="detail-content">
            <div class="detail-header">
              <div class="detail-name">{{ selectedSourceDetail.name }}</div>
              <div class="detail-type" :class="getTypeClass(selectedSourceDetail.pollutionType)">
                {{ selectedSourceDetail.pollutionType }}
              </div>
            </div>
            
            <div class="detail-info">
              <div class="info-item">
                <span class="info-label">地址：</span>
                <span class="info-value">{{ selectedSourceDetail.address }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">联系人：</span>
                <span class="info-value">{{ selectedSourceDetail.contact }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">联系电话：</span>
                <span class="info-value">{{ selectedSourceDetail.phone }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">主要污染物：</span>
                <span class="info-value">{{ selectedSourceDetail.mainPollutants.join('、') }}</span>
              </div>
            </div>
            
            <div class="detail-charts">
              <div class="chart-title">近期排放趋势</div>
              <div ref="sourceChartRef" class="source-chart"></div>
            </div>
            
            <div class="detail-actions">
              <button class="action-btn view-history">查看历史记录</button>
              <button class="action-btn start-monitor">启动重点监控</button>
            </div>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { initMap } from '@/utils/map'
import { AMAP_CONFIG, MAP_CONFIG } from '@/config/map'

// 状态初始化
const currentTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
let timer: number = 0

// 地图相关
const mapContainer = ref<HTMLElement | null>(null)
const map = ref(null)
const currentMapMode = ref('3d')

// 溯源类型
const currentType = ref('air')
const tracingTypes = ref([
  { id: 'air', name: '大气污染溯源', icon: 'air-icon' },
  { id: 'water', name: '水污染溯源', icon: 'water-icon' }
])

// 图表引用
const tracingChartRef = ref<HTMLElement | null>(null)
const sourceChartRef = ref<HTMLElement | null>(null)

// 污染源数据
const pollutionSources = ref([
  {
    id: 1,
    name: '安徽灵璧农牧产业科技有限公司',
    pollutionType: '大气污染',
    matchRate: 87,
    distance: 1.2,
    address: '灵璧县产业园区西南角',
    contact: '张经理',
    phone: '13812345678',
    mainPollutants: ['氨气', '硫化氢', '颗粒物'],
    coordinates: [117.5584, 33.5428],
    type: 'air'
  },
  {
    id: 2,
    name: '灵璧县化工厂',
    pollutionType: '水污染',
    matchRate: 92,
    distance: 0.8,
    address: '灵璧县产业园区东北角',
    contact: '李厂长',
    phone: '13987654321',
    mainPollutants: ['COD', '氨氮', '重金属'],
    coordinates: [117.5634, 33.5478],
    type: 'water'
  },
  {
    id: 3,
    name: '灵璧县塑料制品厂',
    pollutionType: '大气污染',
    matchRate: 65,
    distance: 2.1,
    address: '灵璧县产业园区东侧',
    contact: '王主任',
    phone: '13765432198',
    mainPollutants: ['VOCs', '苯系物', '颗粒物'],
    coordinates: [117.5684, 33.5458],
    type: 'air'
  },
  {
    id: 4,
    name: '灵璧县印染厂',
    pollutionType: '水污染',
    matchRate: 78,
    distance: 1.5,
    address: '灵璧县产业园区南侧',
    contact: '赵经理',
    phone: '13698765432',
    mainPollutants: ['COD', '色度', '硫化物'],
    coordinates: [117.5604, 33.5398],
    type: 'water'
  },
  {
    id: 5,
    name: '灵璧县建材厂',
    pollutionType: '大气污染',
    matchRate: 72,
    distance: 1.8,
    address: '灵璧县产业园区西侧',
    contact: '钱厂长',
    phone: '13567891234',
    mainPollutants: ['粉尘', '二氧化硫', '氮氧化物'],
    coordinates: [117.5534, 33.5448],
    type: 'air'
  }
])

// 选中的污染源
const selectedSource = ref<number | null>(null)
const selectedSourceDetail = computed(() => {
  if (!selectedSource.value) return null
  return pollutionSources.value.find(source => source.id === selectedSource.value)
})

// 根据当前选择的溯源类型过滤污染源
const filteredSources = computed(() => {
  return pollutionSources.value.filter(source => source.type === currentType.value)
})

// 选择污染源
const selectSource = (id: number) => {
  selectedSource.value = id
  
  // 更新地图标记
  if (map.value && map.value.clearMarkers) {
    map.value.clearMarkers()
    
    const source = pollutionSources.value.find(s => s.id === id)
    if (source) {
      map.value.addMarker(source.coordinates, {
        title: source.name,
        icon: source.type === 'air' ? 'air-pollution' : 'water-pollution'
      })
      
      // 居中显示
      map.value.setCenter(source.coordinates)
    }
  }
  
  // 初始化污染源详情图表
  setTimeout(() => {
    if (sourceChartRef.value) {
      initSourceChart()
    }
  }, 100)
}

// 获取匹配度颜色
const getMatchColor = (rate: number) => {
  if (rate >= 80) return '#ff4d4d'
  if (rate >= 60) return '#ffa64d'
  return '#4da6ff'
}

// 获取污染类型样式类
const getTypeClass = (type: string) => {
  if (type.includes('大气')) return 'air-pollution'
  if (type.includes('水')) return 'water-pollution'
  return ''
}

// 地图控制处理
const handleMapControl = (mode: string) => {
  currentMapMode.value = mode
  
  if (!map.value) return
  
  switch (mode) {
    case '2d':
      map.value.mapControl.to2D()
      break
    case '3d':
      map.value.mapControl.to3D()
      break
    case 'satellite':
      map.value.mapControl.toSatellite()
      break
    case 'road':
      map.value.mapControl.toRoad()
      break
  }
}

// 初始化溯源分析图表
const initTracingChart = () => {
  if (!tracingChartRef.value) return
  
  const existingChart = (tracingChartRef.value as any)._echarts_instance_
  if (existingChart) {
    existingChart.dispose()
  }
  
  const tracingChart = echarts.init(tracingChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['监测值', '背景值', '超标率'],
      textStyle: { color: '#fff' },
      right: 10,
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '25%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
        axisLine: { lineStyle: { color: '#0ff' } },
        axisLabel: { color: '#fff' }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '浓度',
        nameTextStyle: { color: '#fff' },
        axisLine: { lineStyle: { color: '#0ff' } },
        axisLabel: { color: '#fff' },
        splitLine: { lineStyle: { color: 'rgba(0,255,255,0.1)' } }
      },
      {
        type: 'value',
        name: '超标率',
        nameTextStyle: { color: '#fff' },
        min: 0,
        max: 100,
        interval: 20,
        axisLine: { lineStyle: { color: '#0ff' } },
        axisLabel: {
          formatter: '{value}%',
          color: '#fff'
        },
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '监测值',
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#0ff' },
            { offset: 1, color: 'rgba(0,255,255,0.3)' }
          ])
        },
        data: [4.2, 5.3, 6.1, 5.8, 4.9, 6.3, 7.2]
      },
      {
        name: '背景值',
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#7b7bff' },
            { offset: 1, color: 'rgba(123,123,255,0.3)' }
          ])
        },
        data: [3.1, 3.2, 3.3, 3.2, 3.1, 3.4, 3.3]
      },
      {
        name: '超标率',
        type: 'line',
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: { color: '#ff7b7b' },
        lineStyle: { width: 2, color: '#ff7b7b' },
        data: [35, 65, 85, 78, 58, 85, 118]
      }
    ]
  }
  
  tracingChart.setOption(option)
  tracingChart.resize()
}

// 初始化污染源详情图表
const initSourceChart = () => {
  if (!sourceChartRef.value || !selectedSourceDetail.value) return
  
  const existingChart = (sourceChartRef.value as any)._echarts_instance_
  if (existingChart) {
    existingChart.dispose()
  }
  
  const sourceChart = echarts.init(sourceChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLine: { lineStyle: { color: '#0ff' } },
      axisLabel: { color: '#fff', fontSize: 10 }
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#0ff' } },
      axisLabel: { color: '#fff', fontSize: 10 },
      splitLine: { lineStyle: { color: 'rgba(0,255,255,0.1)' } }
    },
    series: [
      {
        name: '排放量',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0,255,255,0.5)' },
            { offset: 1, color: 'rgba(0,255,255,0.1)' }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        lineStyle: { color: '#0ff' },
        itemStyle: { color: '#0ff' },
        data: [
          Math.round(Math.random() * 100),
          Math.round(Math.random() * 100),
          Math.round(Math.random() * 100),
          Math.round(Math.random() * 100),
          Math.round(Math.random() * 100),
          Math.round(Math.random() * 100),
          Math.round(Math.random() * 100)
        ]
      }
    ]
  }
  
  sourceChart.setOption(option)
  sourceChart.resize()
}

// 定时器
onMounted(async () => {
  // 初始化地图
  if (mapContainer.value) {
    try {
      map.value = await initMap(mapContainer.value, {
        ...MAP_CONFIG,
        ...AMAP_CONFIG
      })
      console.log('溯源地图初始化成功')
      
      // 初始化完成后设置默认模式
      map.value.mapControl.to3D()
      
      // 添加当前类型的所有污染源标记
      filteredSources.value.forEach(source => {
        map.value.addMarker(source.coordinates, {
          title: source.name,
          icon: source.type === 'air' ? 'air-pollution' : 'water-pollution'
        })
      })
    } catch (error) {
      console.error('溯源地图初始化失败:', error)
    }
  }
  
  // 初始化溯源分析图表
  setTimeout(() => {
    initTracingChart()
  }, 300)
  
  // 启动定时器
  timer = setInterval(() => {
    currentTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }, 1000)
})

onUnmounted(() => {
  clearInterval(timer)
  
  // 销毁图表实例
  if (tracingChartRef.value) {
    const chart = (tracingChartRef.value as any)._echarts_instance_
    if (chart) {
      chart.dispose()
    }
  }
  
  if (sourceChartRef.value) {
    const chart = (sourceChartRef.value as any)._echarts_instance_
    if (chart) {
      chart.dispose()
    }
  }
})

// 监听溯源类型变化
watch(currentType, () => {
  // 重置选中的污染源
  selectedSource.value = null
  
  // 更新地图标记
  if (map.value && map.value.clearMarkers) {
    map.value.clearMarkers()
    
    // 添加当前类型的所有污染源标记
    filteredSources.value.forEach(source => {
      map.value.addMarker(source.coordinates, {
        title: source.name,
        icon: source.type === 'air' ? 'air-pollution' : 'water-pollution'
      })
    })
  }
})
</script>

<style lang="scss" scoped>
.pollution-tracing {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #0a2744 0%, #001529 100%);
  color: #fff;
  padding: 5px;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: rgba(0,0,0,0.5);
    border-bottom: 1px solid rgba(0,255,255,0.3);
    margin-bottom: 5px;

    h1 {
      margin: 0;
      font-size: 20px;
      color: #0ff;
    }

    .current-time {
      font-size: 14px;
      color: #fff;
    }
  }

  .page-content {
    display: grid;
    grid-template-columns: 40% 60%;
    gap: 10px;
    flex: 1;
    min-height: 0;
  }

  .left-panel, .right-panel {
    display: flex;
    flex-direction: column;
    gap: 10px;
    overflow: auto;
  }

  .panel-item {
    background: rgba(0,0,0,0.5);
    border: 1px solid rgba(0,255,255,0.3);
    border-radius: 4px;
    padding: 10px;
    display: flex;
    flex-direction: column;

    h3 {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #0ff;
      border-bottom: 1px solid rgba(0,255,255,0.3);
      padding-bottom: 5px;
    }
  }

  // 溯源类型选择器
  .type-selector {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;

    .type-item {
      flex: 1;
      display: flex;
      align-items: center;
      background: rgba(255,255,255,0.05);
      border-radius: 4px;
      padding: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: rgba(0,255,255,0.1);
      }

      &.active {
        background: rgba(0,255,255,0.2);
        border: 1px solid #0ff;
      }

      .type-icon {
        width: 24px;
        height: 24px;
        margin-right: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        background: rgba(255,255,255,0.1);

        &.air-icon::before {
          content: '🌬️';
          font-size: 16px;
        }

        &.water-icon::before {
          content: '💧';
          font-size: 16px;
        }
      }

      .type-name {
        font-size: 12px;
        color: #fff;
      }
    }
  }

  // 污染源列表
  .source-table-container {
    flex: 1;
    overflow: auto;
    margin-bottom: 10px;

    .source-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 12px;

      th, td {
        padding: 8px;
        text-align: left;
        border-bottom: 1px solid rgba(0,255,255,0.1);
      }

      th {
        color: #0ff;
        font-weight: normal;
        background: rgba(0,255,255,0.1);
      }

      tr {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(0,255,255,0.05);
        }

        &.selected {
          background: rgba(0,255,255,0.1);
          border-left: 2px solid #0ff;
        }
      }

      .match-bar-container {
        width: 100%;
        display: flex;
        align-items: center;
        gap: 5px;

        .match-bar {
          height: 4px;
          border-radius: 2px;
          flex: 1;
        }

        span {
          width: 30px;
          text-align: right;
        }
      }
    }
  }

  // 溯源分析图表
  .chart-container {
    height: 200px;
    background: rgba(255,255,255,0.02);
    border-radius: 4px;
  }

  // 溯源地图
  .tracing-map {
    flex: 1;
    display: flex;
    flex-direction: column;

    .map-container {
      flex: 1;
      min-height: 300px;
      background: #333;
      border-radius: 4px;
      position: relative;
    }
  }

  // 污染源详情
  .source-detail {
    flex: 1;
    min-height: 200px;

    .detail-content {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .detail-name {
        font-size: 14px;
        font-weight: bold;
        color: #fff;
      }

      .detail-type {
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 10px;

        &.air-pollution {
          background: rgba(255,123,123,0.2);
          color: #ff7b7b;
        }

        &.water-pollution {
          background: rgba(123,123,255,0.2);
          color: #7b7bff;
        }
      }
    }

    .detail-info {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 8px;

      .info-item {
        font-size: 12px;

        .info-label {
          color: rgba(255,255,255,0.7);
        }

        .info-value {
          color: #fff;
        }
      }
    }

    .detail-charts {
      .chart-title {
        font-size: 12px;
        color: #0ff;
        margin-bottom: 5px;
      }

      .source-chart {
        height: 150px;
        background: rgba(255,255,255,0.02);
        border-radius: 4px;
      }
    }

    .detail-actions {
      display: flex;
      gap: 10px;
      margin-top: 10px;

      .action-btn {
        flex: 1;
        background: rgba(0,0,0,0.5);
        border: 1px solid rgba(0,255,255,0.3);
        color: #fff;
        padding: 8px 0;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background: rgba(0,255,255,0.1);
        }

        &.view-history {
          border-color: #7b7bff;
          color: #7b7bff;
        }

        &.start-monitor {
          border-color: #ff7b7b;
          color: #ff7b7b;
        }
      }
    }
  }
}
</style> 